package org.amphiprion.montrictracv4.db.adapter;

import java.util.List;

import org.amphiprion.montrictracv4.App;
import org.amphiprion.montrictracv4.R;
import org.amphiprion.montrictracv4.db.model.GameExtension;
import org.amphiprion.montrictracv4.fragment.dialog.ExtensionListFragment;

import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ExtensionListAdapter extends ArrayAdapter<GameExtension> {

	FragmentActivity context;
	int layoutResourceId;
	List<GameExtension> data = null;
	ExtensionListFragment extensionListFragment;

	public ExtensionListAdapter(FragmentActivity paramFragmentActivity,
			ExtensionListFragment extensionListFragment, int layoutResourceId,
			List<GameExtension> data) {
		super(paramFragmentActivity, layoutResourceId, data);
		this.layoutResourceId = layoutResourceId;
		this.extensionListFragment = extensionListFragment;
		this.context = paramFragmentActivity;
		this.data = data;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		ItemHolder holder = null;

		if (row == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			row = inflater.inflate(layoutResourceId, parent, false);

			holder = new ItemHolder();
			holder.imgLang = (ImageView) row.findViewById(R.id.imgLang);
			holder.imgIcon = (ImageView) row.findViewById(R.id.imgIcon);
			holder.imgOwned = (ImageView) row.findViewById(R.id.imgOwned);

			holder.txtTitle = (TextView) row.findViewById(R.id.txtTitle);
			row.setTag(holder);
		} else {
			holder = (ItemHolder) row.getTag();
		}

		GameExtension item = data.get(position);
		holder.txtTitle.setText(item.name);

		if (item.owned) {
			holder.imgOwned.setVisibility(View.VISIBLE);
		} else {
			holder.imgOwned.setVisibility(View.INVISIBLE);
		}
		// image
		if (item.image != null) {
			App.setUrlDrawable(holder.imgIcon, item.image,
					context.getSupportFragmentManager());
		}

		// lang
		if (item.lang.image != null) {
			App.setUrlDrawable(holder.imgLang, item.lang.image,
					context.getSupportFragmentManager());
		}
		return row;
	}

	static class ItemHolder {
		ImageView imgLang;
		ImageView imgOwned;
		ImageView imgIcon;
		TextView txtTitle;
	}

}
